package com.example.birdfriends.controller;

import com.example.birdfriends.pojo.follow.Follower;
import com.example.birdfriends.pojo.post.Post;
import com.example.birdfriends.pojo.post.PostFront;
import com.example.birdfriends.pojo.post.PostsAndAuthors;
import com.example.birdfriends.pojo.praise.Praise;
import com.example.birdfriends.pojo.recommend.Recommend;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.service.*;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.post.PostUtil;
import com.example.birdfriends.utils.result.Result;
import com.example.birdfriends.utils.search.SearchUtil;
import com.example.birdfriends.utils.wordSplice.CutWord;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RequestMapping("/praise")
@RestController
public class PraiseController extends SearchController {
    @Autowired
    private PraiseService praiseService = null;
    @Autowired
    private PostService postService = null;
    @Autowired
    private ConvertService convertService = null;
    @Autowired
    private Result result = null;
    @Autowired
    private RecommendService recommendService;
    @Autowired
    private FollowService followService;
    @Autowired
    private PostUtil postUtil;

    private Object getDataByCurPage(PostFront postFront) throws IOException {
        // 在首页点赞，根据当前是否有用户登录返回所需的不同数据
        Long curLoginUid = postFront.getCurLoginUid();  // 当前登录的用户，用户未登录无法点赞，因此点赞时该字段必不为空
        String curPage = postFront.getCurPage();  // 当前点赞的页面
        if (curPage.equals("main")){
            String tabName = postFront.getTabName();  // 标签名，根据标签名返回不同的数据
            Long curPageNumber = postFront.getCurPageNumber();

            long lineNumber = 50;
            long start = (curPageNumber - 1) * lineNumber;
            System.out.println("当前页面是main");
            List<Post> posts = new ArrayList<>();
            switch (tabName) {
                case "推荐":
                    // 推荐标签页，从推荐表中获取数据
                    Recommend recommend = recommendService.findRecommendByCurLoginUid(curLoginUid);
                    if (recommend != null) {  // 推荐数据项存在，从推荐数据项中加载数据
                        List<String> recommendPidStrList = convertService.string2List(recommend.getPidList());
                        List<Post> recPosts = new ArrayList<>();
                        for (String pid : recommendPidStrList) {
                            recPosts.add(postService.findPostByPid(Long.parseLong(pid)));
                        }
                        int end = (int) (start + lineNumber);
                        if (end > recPosts.size()) end = recPosts.size();
                        posts = recPosts.subList((int) start, end);
                    } else {
                        // 推荐数据项不存在，从posts数据表中查询
                        posts = postService.queryPostWithLoginInMain(curLoginUid, start, lineNumber);
                    }
                    return convertService.findPostsAuthors(posts, curLoginUid, curPage);
                case "热榜":
                    // 在热榜页点赞
                    posts = postService.findHotPostIdList();
                    return convertService.findPostsAuthors(posts, curLoginUid, curPage);
                case "关注":
                    // 在关注标签页点赞
                    List<Long> followedUidList = followService.findFollowedUidsByCurUid(curLoginUid);
                    return postUtil.findMyFollowUsersAndPosts(followedUidList, curLoginUid);
                default:
                    // 在主题标签页点赞
                    if (curLoginUid == null) {
                        posts = postService.findPostsByThemeNotLogin(tabName, start, lineNumber);
                    } else {
                        posts = postService.findPostsByThemeWithLogin(tabName, curLoginUid, start, lineNumber);
                    }

                    return convertService.findPostsAuthors(posts, curLoginUid, curPage);
            }
        }
        if (curPage.equals("userDetail")){
            // 用户详情页点赞，获取当前用户的所有帖子
            List<Post> posts = postService.findPostsByUid(curLoginUid);
            return convertService.findPostsAuthors(posts, curLoginUid, curPage);
        }
        if(curPage.equals("postDetail")){
            Long pid = postFront.getPid();
            Post post = postService.findPostByPid(pid);
            return convertService.findPostAuthor(post, curLoginUid, curPage);
        }
        if (curPage.equals("search")){
            String searchContent = postFront.getSearchContent();
            List<PostFront> postList = searchPostMap.get(searchContent);
            int pageNumber = Math.toIntExact(postFront.getCurPageNumber());
            int lineNumber = 50;
            int start = (pageNumber - 1) * lineNumber;

            if (postList == null){
                List<String> words = cutWord.cutSentence(postFront.getSearchContent());
                postList = searchUtil.searchPost(words, curLoginUid, curPage);
                searchPostMap.put(searchContent, postList);
            }
            int endIndex = start + lineNumber;
            if (endIndex > postList.size()) endIndex = postList.size();
            List<PostFront> posts = postList.subList(start, endIndex);
            return convertService.findAuthors(posts);
        }

        return null;
    }

    @Autowired
    private SearchUtil searchUtil;
    @Autowired
    private CutWord cutWord;

    @PostMapping("/insertInListUser")  // 在用户详情帖子列表中点赞
    public Map<String, Object> addPraise(@RequestBody PostFront postFront) throws IOException {
        Long pid =  postFront.getPid();
        Long curLoginUid = postFront.getCurLoginUid();  // 当前登录的用户
        Timestamp createAt = new Timestamp(System.currentTimeMillis());  // 创建日期

        // 设置Praise的数据
        Praise praise = new Praise();
        praise.setPid(pid); praise.setUid(curLoginUid); praise.setCreateAt(createAt);
        // 使用更新措施
        int addPraise = praiseService.praisePost(praise);
        boolean success = addPraise > 0;
        // 添加完数据之后，统计当前帖子的点赞数，(以及isActive=true，不管的话应该也行)
        Object postsAndAuthors = getDataByCurPage(postFront);
        if (success){
            // 最后返回postFront
            return result.resultMap(true, "点赞成功", postsAndAuthors);
        }

        return result.resultMap(false, "点赞失败", postsAndAuthors);
    }

    @PostMapping("/deleteInListUser")  // 在用户列表界面取消点赞
    public Map<String, Object> cancelPraiseInUserDetail(@RequestBody PostFront postFront) throws IOException {
        Long pid = postFront.getPid(); Long curLoginUid = postFront.getCurLoginUid();   // uid是目前登录的用户id
        int delete = praiseService.deletePraise(pid, curLoginUid);  // 取消点赞
        boolean success = delete > 0;

        Object postsAndAuthors = getDataByCurPage(postFront);
        if(success){
            // 取消成功，那么我现在重新获取当前用户的post
            return result.resultMap(true, "取消点赞成功", postsAndAuthors);
        }

        return result.resultMap(false, "取消点赞失败", postsAndAuthors);
    }

    @Autowired
    private UserService userService = null;

    @PostMapping("/queryPostLovers")
    public Map<String, Object> queryPostLovers(@RequestBody PostFront postFront){
        Long pid = postFront.getPid();
        System.out.println("pid:"+pid);
        List<Long> uidsInPraises = praiseService.findUidsInPraisesByPid(pid);  // 某篇帖子点赞的用户的id
        // 因为一个用户只能点赞一篇帖子一次，所以uid不存在重复
        boolean success = uidsInPraises != null && uidsInPraises.size() > 0;
        if(success){
            List<User> lovers = new ArrayList<>();
            for(Long uid: uidsInPraises){
                User lover = userService.findUserByUid(uid);
                lovers.add(lover);
            }

            return result.resultMap(true, "查询成功", lovers);
        }
        return result.resultMap(false, "还没有人点赞，快来点个赞吧", null);
    }
}
